package com.adan.content.service.impl;

import com.adan.base.execption.XcPlusException;
import com.adan.base.model.PageParams;
import com.adan.base.model.PageResult;
import com.adan.content.mapper.CourseBaseMapper;
import com.adan.content.model.dto.AddCourseDto;
import com.adan.content.model.dto.CourseBaseInfoDto;
import com.adan.content.model.dto.EditCourseDto;
import com.adan.content.model.dto.QueryCourseParamsDto;
import com.adan.content.model.po.*;
import com.adan.content.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 课程基本信息 服务实现类
 * </p>
 *
 * @author adan
 */
@Slf4j
@Service
public class CourseBaseServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements CourseBaseService {

    @Resource
    private CourseMarketService courseMarketService;
    @Resource
    private CourseCategoryService courseCategoryService;
    @Resource
    private CourseBaseService courseBaseService;
    @Resource
    private CourseTeacherService courseTeacherService;
    @Resource
    private TeachplanService teachplanService;


    @Override
    public PageResult<CourseBase> queryCourseBaseList(long companyId, PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {
        // 1.构建条件查询
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        String auditStatus = queryCourseParamsDto.getAuditStatus();
        // 课程审核状态
        String publishStatus = queryCourseParamsDto.getPublishStatus();
        // 课程发布状态
        String courseName = queryCourseParamsDto.getCourseName();
        //机构id
        queryWrapper.eq(CourseBase::getCompanyId,companyId);
        queryWrapper.eq(StringUtils.isNotEmpty(auditStatus), CourseBase::getAuditStatus, auditStatus);
        queryWrapper.eq(StringUtils.isNotEmpty(publishStatus), CourseBase::getStatus, publishStatus);
        queryWrapper.like(StringUtils.isNotEmpty(courseName), CourseBase::getName, courseName);
        // 2.构建分页查询
        Page<CourseBase> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        // 3.查询数据
        Page<CourseBase> pageResult = this.page(page, queryWrapper);
        // 粉装结果返回
        PageResult<CourseBase> result = new PageResult<>(pageResult);
        long pages = pageResult.getCurrent();
        // 总页数
        long pages2 = pageResult.getPages();
        long size = pageResult.getSize();
        log.error("当前页：{}, 分页大小：{}, 页数：{}", pages, size, pages2);
        return result;
    }

    @Transactional
    @Override
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto courseDto) {
        // 合法性校验
        /* if (StringUtils.isBlank(courseDto.getName())) {
            throw new RuntimeException("课程名称为空");
        }

        if (StringUtils.isBlank(courseDto.getMt())) {
            throw new RuntimeException("课程分类为空");
        }

        if (StringUtils.isBlank(courseDto.getSt())) {
            throw new RuntimeException("课程分类为空");
        }

        if (StringUtils.isBlank(courseDto.getGrade())) {
            throw new RuntimeException("课程等级为空");
        }

        if (StringUtils.isBlank(courseDto.getTeachmode())) {
            throw new RuntimeException("教育模式为空");
        }

        if (StringUtils.isBlank(courseDto.getUsers())) {
            throw new RuntimeException("适应人群为空");
        }

        if (StringUtils.isBlank(courseDto.getCharge())) {
            throw new RuntimeException("收费规则为空");
        } */
        // 新增对象
        CourseBase courseBase = new CourseBase();
        // 将填写的课程信息赋值给新增对象
        BeanUtils.copyProperties(courseDto, courseBase);
        // 设置审核状态(未审核)
        courseBase.setAuditStatus("202002");
        // 设置发布状态(未发布)
        courseBase.setStatus("203001");
        // 机构id
        courseBase.setCompanyId(companyId);
        // 添加时间
        courseBase.setCreateDate(LocalDateTime.now());
        // 1.保存课程基本信息数据
        boolean save = this.save(courseBase);
        if (!save) {
            throw new RuntimeException("新增课程基本信息失败");
        }

        // 2.向课程营销表保存课程营销信息
        // 封装课程营销信息
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(courseDto, courseMarket);
        // 设置课程id
        Long courseId = courseBase.getId();
        courseMarket.setId(courseId);
        //保存课程营销信息
        boolean flag = courseBaseService.saveOrUpdateCourseMarket(courseMarket);
        if (!flag){
            XcPlusException.cast("新增课程营销信息失败");
        }

        // 3.查询课程基本信息及营销信息并返回
        return queryCourseBaseById(courseId);
    }

    /**
     * 保存课程营销信息
     * @param courseMarket 课程营销信息
     * @return boolean
     */
    @Transactional
    public boolean saveOrUpdateCourseMarket(CourseMarket courseMarket) {
        // 判断收费规则，若课程收费，则价格必须大于0
        String charge = courseMarket.getCharge();
        if ("201001".equals(charge)) {
            // 收费
            Float price = courseMarket.getPrice();
            if (price == null || price <= 0) {
                XcPlusException.cast("课程设置了收费，价格不能为空，且必须大于0");
            }
        }
        return courseMarketService.saveOrUpdate(courseMarket);
    }

    @Override
    @Transactional
    public void removeCourse(Long companyId, Long courseId) {
        // 删除课程需要删除课程相关的基本信息、营销信息、课程计划、课程教师信息。
        CourseBase courseBase = this.getById(courseId);
        if (!courseBase.getCompanyId().equals(companyId)){
            XcPlusException.cast("只允许删除本机构的课程");
        }
        // 删除课程教师信息
        courseTeacherService.remove(
                new LambdaQueryWrapper<CourseTeacher>().eq(CourseTeacher::getCourseId, courseId)
        );
        // 删除课程计划
        teachplanService.remove(
                new LambdaQueryWrapper<Teachplan>().eq(Teachplan::getCourseId, courseId)
        );
        // 删除营销信息
        courseMarketService.removeById(courseId);
        // 删除营销信息
        courseBaseService.removeById(courseId);
    }


    /**
     * 根据课程id查询课程基本信息及营销信息
     * @param courseId 课程id
     * @return CourseBaseInfoDto
     */
    public CourseBaseInfoDto queryCourseBaseById(Long courseId) {
        // 1.查询课程基本信息
        CourseBase courseBase = this.getById(courseId);
        if (courseBase == null) {
            return null;
        }
        // 2.查询课程营销信息
        CourseMarket courseMarket = courseMarketService.getById(courseId);
        // 3. 封装返回结果信息
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        // 3.1 拷贝课程基本信息属性
        BeanUtils.copyProperties(courseBase, courseBaseInfoDto);
        // 3.2 设置大小分类名称
        CourseCategory courseCategoryMt = courseCategoryService.getById(courseBase.getMt());
        CourseCategory courseCategorySt = courseCategoryService.getById(courseBase.getSt());
        courseBaseInfoDto.setMtName(courseCategoryMt.getName());    // 大分类名称
        courseBaseInfoDto.setStName(courseCategorySt.getName());    // 小分类名称
        // 3.3 拷贝课程营销信息
        if (courseMarket != null) {
            BeanUtils.copyProperties(courseMarket, courseBaseInfoDto);
        }
        return courseBaseInfoDto;
    }

    @Override
    @Transactional
    public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto editCourseDto) {
        // 1.修改课程基本信息
        Long courseId = editCourseDto.getId();
        CourseBase courseBase = this.getById(courseId);
        //判断机构id（本机构只能修改本机构的课程）
        if (!companyId.equals(courseBase.getCompanyId())){
            XcPlusException.cast("本机构只能修改本机构的课程");
        }
        //封装修改的课程信息
        BeanUtils.copyProperties(editCourseDto, courseBase);
        courseBase.setChangeDate(LocalDateTime.now());
        //更新数据块
        this.updateById(courseBase);
        // 2.修改课程营销信息
        CourseMarket courseMarket = courseMarketService.getById(courseId);
        // 由于课程营销信息不是必填项，故这里先判断一下
        if (courseMarket == null){
            courseMarket = new CourseMarket();
        }
        // 对象拷贝
        BeanUtils.copyProperties(editCourseDto, courseMarket);
        // 有则更新，无则插入
        boolean flag = courseBaseService.saveOrUpdateCourseMarket(courseMarket);
        if (!flag){
            XcPlusException.cast("修改课程营销信息失败");
        }
        return queryCourseBaseById(courseId);
    }
}
